package com.nari.ncps.screen.service.impl.dryport;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nari.ncps.screen.entity.dryport.DryportRealtimeTqi;
import com.nari.ncps.screen.entity.dryport.DryportRealtimeTrain;
import com.nari.ncps.screen.mapper.dryport.DryportRealtimeTqiMapper;
import com.nari.ncps.screen.mapper.dryport.DryportRealtimeTrainMapper;
import com.nari.ncps.screen.service.dryport.*;
import com.nari.ncps.screen.vo.dryport.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 路港详情信息 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-10-26
 */
@Service
public class DryportDetailInfoServiceImpl implements DryportDetailInfoService {

    @Autowired
    private DryportOpermonLocomotiveService locomotiveService;
    
    @Autowired
    private DryportOpermonCarService carService;
    
    @Autowired
    private DryportOpermonShipService shipService;
    
    @Autowired
    private DryportProdoperGoodsSendService goodsSendService;

    @Autowired
    private DryportRealtimeTrainMapper dryportRealtimeTrainMapper;

    @Autowired
    private DryportRealtimeTqiMapper dryportRealtimeTqiMapper;

    @Override
    public WeatherInfoVO getWeatherInfo(String orgCode) {
        WeatherInfoVO vo = new WeatherInfoVO();
        
        // 天气信息可对接第三方天气API，目前提供模拟数据
        // 日夜平均湿度：45%-65%
        int humidity = 50 + (int)(Math.random() * 15);
        vo.setDayNightHumidity(humidity + "%");
        
        // 水温状况：根据季节设置合理范围
        int month = LocalDate.now().getMonthValue();
        int waterTemp = 0;
        if (month >= 12 || month <= 2) {
            waterTemp = -2 + (int)(Math.random() * 5); // 冬季：-2°C到3°C
        } else if (month >= 3 && month <= 5) {
            waterTemp = 8 + (int)(Math.random() * 8); // 春季：8°C到16°C
        } else if (month >= 6 && month <= 8) {
            waterTemp = 22 + (int)(Math.random() * 6); // 夏季：22°C到28°C
        } else {
            waterTemp = 12 + (int)(Math.random() * 8); // 秋季：12°C到20°C
        }
        vo.setWaterTemperature(waterTemp + "°C");
        
        return vo;
    }
    
    @Override
    public TrainRealtimeInfoVO getTrainRealtimeInfo(String orgCode) {
        if(orgCode==null) {
            orgCode = "100360";
        }
        TrainRealtimeInfoVO vo = new TrainRealtimeInfoVO();
        DryportRealtimeTrain train = new DryportRealtimeTrain();
        LambdaQueryWrapper<DryportRealtimeTrain> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DryportRealtimeTrain::getOrgCode, orgCode);
        lqw.orderByDesc(DryportRealtimeTrain::getStatisticTime);

        List<DryportRealtimeTrain> dryportRealtimeTrains = dryportRealtimeTrainMapper.selectList(lqw);

        if(dryportRealtimeTrains!=null&& (!dryportRealtimeTrains.isEmpty())){
            DryportRealtimeTrain dryportRealtimeTrain = dryportRealtimeTrains.stream().findFirst().get();
            BeanUtil.copyProperties(dryportRealtimeTrain,vo);
        }
        return vo;
    }
    
    @Override
    public TrainOperationInfoVO getTrainOperationInfo(String orgCode) {
        TrainOperationInfoVO vo = new TrainOperationInfoVO();
        
        // 基于机车运行数据组装列车运行信息（默认查询昨天）
        LocomotiveStatusVO locomotiveStatus = locomotiveService.getLocomotiveStatus(null, null, null);
        
        if (locomotiveStatus != null && locomotiveStatus.getDataList() != null) {
            List<TrainOperationInfoVO.TrainItem> trainList = new ArrayList<>();
            
            // 基于机车数据模拟列车运行信息
            for (int i = 0; i < Math.min(5, locomotiveStatus.getDataList().size()); i++) {
                TrainOperationInfoVO.TrainItem item = new TrainOperationInfoVO.TrainItem();
                item.setTrainNumber("X" + (i + 1) + "001");
                item.setSpeed((40 + i * 5) + " km/h");
                item.setMileage((120 + i * 20) + " km");
                trainList.add(item);
            }
            vo.setTrainList(trainList);
        }
        return vo;
    }
    
    @Override
    public RailwayTransportInfoVO getRailwayTransportInfo(String orgCode) {
        RailwayTransportInfoVO vo = new RailwayTransportInfoVO();
        
        // 基于货物发送数据统计运量
        if (orgCode != null && !orgCode.isEmpty()) {
            List<com.nari.ncps.screen.entity.dryport.DryportProdoperGoodsSend> recentData = 
                goodsSendService.getLatest30DaysStats();
            
            if (recentData != null && !recentData.isEmpty()) {
                // 计算本月日均运量
                BigDecimal totalTransport = BigDecimal.ZERO;
                for (com.nari.ncps.screen.entity.dryport.DryportProdoperGoodsSend data : recentData) {
                    if (data.getGoodsSendAc() != null) {
                        totalTransport = totalTransport.add(data.getGoodsSendAc());
                    }
                }
                // 转换为万吨并计算日均
                vo.setMonthlyAvgTransport(totalTransport.divide(new BigDecimal(recentData.size()), 2, RoundingMode.HALF_UP)
                    .divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP));
            }
        }
        
        return vo;
    }
    
    @Override
    public RailwayTqiVO getRailwayTqi(String orgCode) {
        RailwayTqiVO vo = new RailwayTqiVO();
        LambdaQueryWrapper<DryportRealtimeTqi> lqw = new LambdaQueryWrapper<>();
        List<DryportRealtimeTqi> dryportRealtimeTqis = dryportRealtimeTqiMapper.selectList(lqw);
        return vo;
    }
    
    @Override
    public PortInfoVO getPortInfo(String orgCode) {
        PortInfoVO vo = new PortInfoVO();
        
        // 基于来船信息组装港口动态信息
        int currentYear = LocalDate.now().getYear();
        List<ShipVO> shipList = shipService.getShipInfoStatistics(currentYear);
        
        if (shipList != null && !shipList.isEmpty()) {
            List<PortInfoVO.PortNewsItem> newsList = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            
            // 基于来船信息生成港口动态
            for (int i = 0; i < Math.min(5, shipList.size()); i++) {
                ShipVO ship = shipList.get(i);
                PortInfoVO.PortNewsItem newsItem = new PortInfoVO.PortNewsItem();
                newsItem.setPublishDate(ship.getEstimatedArrival() != null ? ship.getEstimatedArrival() : sdf.format(new java.util.Date()));
                newsItem.setTitle("船只预计到港通知");
                newsItem.setContent("载重" + ship.getLoadCapacity() + "吨，总吨位" + ship.getTotalTonnage() + "吨，始发港：" + ship.getDeparturePort());
                newsList.add(newsItem);
            }
            vo.setPortNewsList(newsList);
        }
        
        return vo;
    }

}

